<?php

namespace app\admin\command;

use app\admin\model\AuthRule;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;

class Wolk extends Command
{
    protected $model = null;

    protected function configure()
    {
        $this
            ->setName('wolk')
            ->addArgument('name')
            ->setDescription('Time exchange points')
            ->setHelp('定时脚本执行用户行走步数兑换积分');
        //要执行的controller必须一样，不适用模糊查询
    }

    protected function execute(Input $input, Output $output)
    {
        #兑换开关
        $wolkTointegraloff = Db::table('fa_config')->where('name', '=', 'wolkTointegraloff')->value('value');
        if ($wolkTointegraloff == 0) {
            echo '已关闭步数兑换积分功能' . date('Y-m-d H:i:s');
            die();
        }
        #查起始兑换步数
        $wolknum = Db::table('fa_config')->where('name', '=', 'wolknum')->value('value');
        if (empty($wolknum) || $wolknum == 0) {
            echo '起始兑换步数不能为0' . date('Y-m-d H:i:s');
            die();
        }
        $wolknumMax = Db::table('fa_config')->where('name', '=', 'wolknum_max')->value('value');
        #查步数兑换比例
        $wolkTointegral = Db::table('fa_config')->where('name', '=', 'wolkTointegral')->value('value');
        #查询今日运动数据
        $where['createtime'] = strtotime(date('Y-m-d'));
        $wolkData = Db::name('user_wolk')->field(['id,user_id,num'])->where($where)->select();
        foreach ($wolkData as &$v) {
            #判断 是否具有兑换资格
            if ($wolknum < $v['num']) {
                if ($wolknumMax < $v['num']){
                    $v['num'] = $wolknumMax;
                }
                    #进行兑换操作 (步数/最小兑换数)取整 * 比例
                    $integral = bcdiv($v['num'], $wolknum, 0) * $wolkTointegral;
                if ($integral)
                    #增加用户积分
                    Db::name('user')->where('id', '=', $v['user_id'])->setInc('score', (int)$integral);
            }
        }
        //throw new Exception("could not delete all menu");
        $output->info("Build Successed!");
    }
}
